//
//  AppDelegate.swift
//  iOS07-Weibo-LPK
//
//  Created by 罗培克 on 6/23/15.
//  Copyright © 2015 lpk. All rights reserved.
//

import UIKit
import AFNetworking

/// 全局变量,记录用户账号
var sharedUserAccount = UserAccount.loadAccount()
/// 切换根控制器的通知
let LPKSwitchRootVCNotification = "LPKSwitchRootVCNotification"

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // 设置外观
        setUpAppearance()
        setUpNetwork()
        
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        window?.backgroundColor = UIColor.redColor()
        window?.rootViewController = defaultViewController()
        
        window?.makeKeyAndVisible()
        
        // 注册通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "switchViewController:", name: LPKSwitchRootVCNotification, object: nil)
        
        return true
    }
    
    /// 切换控制器
    func switchViewController(n: NSNotification) {
        let isMainVc = n.object as! Bool
        window?.rootViewController = isMainVc ? MainViewController() : WelcomeViewController()
    }
    
    /// 判断加载的默认控制器
    private func defaultViewController() -> UIViewController {
        if sharedUserAccount != nil {
            return isNewUpdate() ? NewfeatureController() : WelcomeViewController()
        }
        
        return MainViewController()
//        return NewfeatureController()
    }
    
    /// 是否新版本
    private func isNewUpdate() -> Bool {
        
        // 1. 获取当前版本
        let currentVersion = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as!  String
        let version = NSNumberFormatter().numberFromString(currentVersion)!.doubleValue
        // Swift2.0 ,可以直接转
//        let version = Double(currentVersion)!
        // 2. 从用户偏好设置里获取之前版本
        let versionKey = "versionKey"
        let sandBoxVersion = NSUserDefaults.standardUserDefaults().doubleForKey(versionKey)
        // 3. 将当前版本写入用户偏好
        NSUserDefaults.standardUserDefaults().setDouble(version, forKey: versionKey)
        
        return version > sandBoxVersion
    }
    
    private func setUpAppearance() {
        UINavigationBar.appearance().tintColor = UIColor.orangeColor()
        UITabBar.appearance().tintColor = UIColor.orangeColor()
    }
    
    private func setUpNetwork() {
        // 设置网络指示器
        AFNetworkActivityIndicatorManager.sharedManager().enabled = true
        // 设置网络缓存
        let urlCache = NSURLCache(memoryCapacity: 4 * 1024 * 1024, diskCapacity: 20 * 1024 * 1024, diskPath: nil)
        NSURLCache.setSharedURLCache(urlCache)
    }
}

